$('#top').load('top.html');
$('#bottom').load('bottom.html');
// ---

// 获取元素
const cartBox = document.querySelector('.cartBox')
const totalPriceBox = document.querySelector('.totalPrice')
const totalNum = document.querySelector('.totalNum')
const allSelect = document.querySelector('.allSelect')
const content = document.querySelector('.content')

const id = window.localStorage.getItem('id')
const token = window.localStorage.getItem('token')

testLogin()

function testLogin() {
    const login = window.localStorage.getItem('login')

    // 判断是否有 login
    if (login !== '1') {
        // 没有登录过
        window.localStorage.setItem('url', 'cart')

        window.location.href = './login.html'
        return
    }

    getList()
}

function getList() {
    // 请求购物车列表数据
    const xhr = new XMLHttpRequest()

    xhr.open('GET', 'http://localhost:8888/cart/list?id=' + id)

    xhr.onload = function () {
        const res = JSON.parse(xhr.responseText)

        if (res.code !== 1) {
            // 请求不成功
            window.localStorage.setItem('url', 'cart')
            window.location.href = './login.html'
            return
        }

        bindHtml(res)
    }

    xhr.setRequestHeader('authorization', token)

    xhr.send()
}

// 购物车渲染页面
function bindHtml(res) {
    let str = ''
    res.cart.forEach(item => {
        str += `
      <li>
        <div class="select">
          <input data-id="${ item.goods_id }" class="select_item" type="checkbox" ${ item.is_select ? 'checked' : '' }>
        </div>
        <div class="show">
          <img src="${ item.img_small_logo }" alt="">
        </div>
        <div class="title">
          ${ item.title }
        </div>
        <div class="price">
          ￥ ${ item.current_price }
        </div>
        <div class="number">
          <button>-</button>
          <input type="text" value="${ item.cart_number }">
          <button class="add" data-id="${ item.goods_id }">+</button>
        </div>
        <div class="subprice">
          ￥ ${ (item.current_price * item.cart_number).toFixed(2) }
        </div>
        <div class="del">
          <button>删除</button>
        </div>
      </li>
    `
    })

    cartBox.innerHTML = str

    //渲染全选按钮, 购买总数, 总价格
    let selectNum = 0,
        buyNum = 0,
        totalPrice = 0
    res.cart.forEach(item => {
        if (item.is_select) {
            selectNum++
            buyNum += item.cart_number
            totalPrice += item.cart_number * item.current_price
        }
    })

    allSelect.checked = res.cart.length === selectNum
    totalNum.innerHTML = '购买总数 : ' + buyNum
    totalPriceBox.innerHTML = '总价格 : ' + totalPrice.toFixed(2)
}

// 购物车页面的所有事件
content.addEventListener('click', async e => {
    e = e || window.event
    const target = e.target || e.srcElement

    // 3-2. 判断修改选中
    if (target.className === 'select_item') {
        // 点击的是选中按钮
        // 拿到商品 id
        const goods_id = target.dataset.id

        // 3-3. 发送请求
        const res = await pAjax({
            url: 'http://localhost:8888/cart/select',
            method: 'POST',
            data: `id=${ id }&goodsId=${ goods_id }`,
            dataType: 'json',
            token: token
        })

        // 3-4. 从新打开页面
        getList()
    }

    // 3-3. 判断修改数量增加
    if (target.className === 'add') {
        // 拿到商品 id 和目前的购买数量
        const goods_id = target.dataset.id
        const number = target.previousElementSibling.value - 0 + 1

        // 发送请求
        const res = await pAjax({
            url: 'http://localhost:8888/cart/number',
            method: 'POST',
            data: `id=${ id }&goodsId=${ goods_id }&number=${ number }`,
            dataType: 'json',
            token: token
        })

        // 刷新页面
        getList()
    }

})